#coding:utf-8
import SocketServer
import re
from socket import *
#接收来自浏览的数据，并转发给服务器。

ADDR = ("127.0.0.1", 8081)
def getHost(DataPack):
	result = re.search(r"Host:\s(.*?)\s", DataPack)#将地址返回，如www.baidu.com
	host = result.group(1)
	return host


class MyProxy(SocketServer.BaseRequestHandler):

	def handle(self):
		while True:
			#接收来自浏览器的数据
			self.HttpRqst = self.request.recv(1024)
			print "recv_data_from_cli",self.HttpRqst
			if self.HttpRqst:
				#获取发送目标的host
				self.RHOST = getHost(self.HttpRqst)
				print "get host:",self.RHOST

				#建立一个sock用于转发数据给目标host
				newSock = socket(AF_INET, SOCK_STREAM)
				newSock.connect((str(self.RHOST), 80))
				newSock.send(self.HttpRqst)
				buffer = []

				while True:
					#通讯循环，用于接收来自目标host的数据
					data = newSock.recv(1024)
					if data:
						buffer.append(data)
						print "recv_data_from_ser",data,"\n",type(data)
					else:
						print "have not data from cli"
						break
				print "recv data end",buffer
				self.HttpRspn = "".join(buffer)

				print 
				print "\nreturn_cli_data= ", self.HttpRspn

				# 将接收的数据发送给浏览器
				self.request.sendall(self.HttpRspn)

				print "send cli data success."
			else:
				break
				print "recv cli not data"

if __name__ == "__main__":
	s = SocketServer.ThreadingTCPServer(ADDR, MyProxy)
	s.serve_forever()
